package org.raymond.icloud.common.starter.webFilter;

import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Sets;
import org.raymond.icloud.common.core.util.FilterUtil;
import org.raymond.icloud.common.core.util.RequestUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

@Slf4j
public abstract class AbstractFilter extends OncePerRequestFilter {
    private static final AntPathMatcher ignoresMatch = new AntPathMatcher();
    protected Set<String> ignores = Sets.newLinkedHashSet(
            "/common/public-key"
    );

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException{
        String method = request.getMethod();
        if(StringUtils.equalsIgnoreCase(method, Method.POST.name())) {
            log.debug("{} request: {}", getFilterName(), FilterUtil.getRequestString(request));
        }
        if(StringUtils.equalsIgnoreCase(method, Method.GET.name())) {
            log.debug("{} request: {}", getFilterName(), FilterUtil.getRequestParams(request));
        }
        doFilterSub(request, response, filterChain);
        log.debug("{} response: {}", getFilterName(), FilterUtil.getResponseString(response));
    }

    protected abstract void doFilterSub(HttpServletRequest var1, HttpServletResponse var2, FilterChain var3) throws ServletException, IOException;

    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if(FilterUtil.ignoreMethod(request)) return true;

        String contextPath = request.getContextPath();
        String originRequestUri = request.getRequestURI();
        final String requestUri = originRequestUri.substring(contextPath.length());

        return RequestUtil.notCheck(requestUri)
                || ignores.stream().anyMatch(e->ignoresMatch.match(e, requestUri));
    }
}
